package marchsoft.modules.tiku.config;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import marchsoft.base.PageVO;
import marchsoft.modules.tiku.entity.EStudyData;
import marchsoft.modules.tiku.entity.dto.EStudyDataDto;
import marchsoft.modules.tiku.entity.dto.StudyDataQueryCriteria;
import marchsoft.modules.tiku.service.IEStudyDataService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Description：
 *
 * @author zhansiyu
 * Date: 2022/4/19 9:47
 **/
@Component
@Slf4j
@RequiredArgsConstructor
public class StudyDataRunner implements ApplicationRunner{
    private final RestHighLevelClient restHighLevelClient;
    private final IEStudyDataService studyDataService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 查询所有的学习资料数据，加载到es中
        log.info("往es中存储数据开始------------");
        PageVO pageVO = new PageVO();
        pageVO.setSize(-1);
        pageVO.setCurrent(-1);
        IPage<EStudyDataDto> eStudyDataIPage = studyDataService.getAll(new EStudyDataDto(),pageVO);
        List<EStudyDataDto> records = eStudyDataIPage.getRecords();
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (EStudyDataDto record : records) {
            bulkRequest.add(new IndexRequest("study_data").source(JSON.toJSONString(record), XContentType.JSON));
        }
        restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);


        log.info("es存储数据结束----------------");
    }
}
